package PhoneDept;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * 从互联网获取手机号码归属地信息
 * 访问地址：http://vip.showji.com/locating/?m=
 * @author tiger
 *
 */
public class GetPhoneInfo {
    private static final Log log = LogFactory.getLog(GetPhoneInfo.class);
    
    public static void main(String[] args) {
        // String chinacugsm [] =
        // {"130","131","132","145","155","156","185","186"};//中国联通
        String chinamobile[] = { "134", "135", "136", "137", "138", "139", "147", "150", "151", "152", "157", "158",
                "159", "182", "187", "188" };// 中国移动
        // String chinatel [] = {"133","153","180","189"};//中国电信
        GetPhoneInfo.getPhoneDept(chinamobile);
    }
    
    /**
     * 
     * @param _str 手机号码前三位
     */
    public static void getPhoneDept(String[] _str) {
        log.info("getPhoneDept start:" + System.currentTimeMillis());
        // 获取手机号码
        List<String> phoneList = getPhoneList(_str);
        List<Map<String, String>> fileList = new ArrayList<Map<String, String>>();
        //根据手机号码获取归属地信息
        if (null != phoneList && phoneList.size() > 0) {
            for (String phone : phoneList) {
                HttpClient client = new DefaultHttpClient();
                HttpHost proxy = new HttpHost("proxy-bj1.petrochina", 8080);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
                String url = "http://vip.showji.com/locating/?m=" + phone;
                HttpPost post = new HttpPost(url);
                
                Map<String, String> tmpMap = new Hashtable<String, String>();
                try {
                    HttpResponse resonse = client.execute(post);
                    log.info("响应返回值:" + resonse.getStatusLine().getStatusCode());
                    if (resonse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        HttpEntity entity = resonse.getEntity();
                        if (entity != null) {
                            //byte[] data = EntityUtils.toByteArray(entity);
                            String html = EntityUtils.toString(entity);
                            tmpMap.put(phone, html);
                            //System.out.println(html);
                            // Document doc = Jsoup.parse(html,"utf-8");
                        }
                    } else {
                        //存放查询不到的数据
                        tmpMap.put(phone, String.valueOf(resonse.getStatusLine().getStatusCode()));
                    }
                    fileList.add(tmpMap);
                } catch (Exception e) {
                    log.info(System.currentTimeMillis());
                    log.debug("getPhoneDept Exception:", e);
                } finally {
                    client.getConnectionManager().shutdown();
                }
            }
            
        }
        //写文件，将查询到的数据写入到文件中
        writeResult(fileList);
        log.info("getPhoneDept end:" + System.currentTimeMillis());
    }
    
    private static List<String> getPhoneList(String[] _str) {
        log.info("getPhoneList start:" + System.currentTimeMillis());
        List<String> phoneList = new ArrayList<String>();
        if (null != _str && _str.length > 0) {
            for (String str : _str) {
                for (int i = 0; i <= 9999; i++) {
                    int iLen = String.valueOf(i).length();
                    String tmp = "";
                    switch (iLen) {
                        case 1:
                            tmp = "000" + i;
                            break;
                        case 2:
                            tmp = "00" + i;
                            break;
                        case 3:
                            tmp = "0" + i;
                            break;
                        case 4:
                            tmp = tmp + i;
                            break;
                        default:
                            break;
                    }
                    //构造手机号码前七位
                    String phone = str + tmp;
                    phoneList.add(phone);
                }
            }
        }
        log.info("getPhoneList end:" + System.currentTimeMillis());
        return phoneList;
    }
    
    private static void writeResult(List<Map<String, String>> list) {
        log.info("writeResult start:" + System.currentTimeMillis());
        WriteFile wf = new WriteFile();
        if (null != list && list.size() > 0) {
            String fileCon = "";
            for (Map<String, String> map : list) {
                Iterator<String> iterator = map.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    String value = map.get(key);
                    fileCon = key + ":" + value;
                    wf.write("d:/phone", key + ".xml", fileCon, true, "utf-8");
                }
            }
        }
        log.info("writeResult end:" + System.currentTimeMillis());
    }
}